import axios from 'axios'
import { MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { logError } from './logError'

// create an axios instance
const service = axios.create({
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    logError('api', '请求错误', error, false) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data

    // 如果自定义 code 不为 0，则认为此次请求有问题
    if (res.code !== 0) {
      const { url } = response.config
      logError('api', url, res.message)

      // 401: Illegal token;
      if (res.code === 401) {
        // 重新登陆
        MessageBox.confirm('您的登陆状态已过期，是否要重新登陆', '退出确认', {
          confirmButtonText: '重新登陆',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    logError('api', '响应错误', error.message, false) // for debug
    return Promise.reject(error)
  }
)

export default service
